import { Context } from 'koa';

const { isEmpty, isNotBestAdm, isNotAdm, idIsNotAdm } = require('../constants/err.type');
const { getInfoById } = require('../service/admUsers.service')

// 判断是否输入了logname
const lognameExisted = async (ctx: Context, next: () => Promise<void>) => {
    try {
        const logname = ctx.query.logname
        if(!logname) {
            return ctx.app.emit('error', isEmpty, ctx)
        }
        await next();
    } catch {
        return console.error('判断输入参数错误')
    }
}

// 判断当前admId是否存在
const admIdisExist = async (ctx: Context, next: () => Promise<void>) => {
    try {
        const id = ctx.params.id
        if(!id) {
            return ctx.app.emit('error', isEmpty, ctx)
        }
        const res = await getInfoById(id)
        if(!res) {
            ctx.app.emit('error', idIsNotAdm, ctx)
            return;
        }
        await next();
    } catch {
        return console.error('判断输入参数错误')
    }
}

// 判断是不是最高管理员
const isTheBestRole = async (ctx: Context, next: () => Promise<void>) => {
    try {
        const user = ctx.state.user
        if(user.role !== 128) {
            return ctx.app.emit('error', isNotBestAdm, ctx)
        }
        await next()
    } catch {
        return console.error('判断是不是最高管理员错误')
    }
}

// 判断新参数是不是管理员
const checkRoleisAdm = async (ctx: Context, next: () => Promise<void>) => {
    try {
        const newAdm = ctx.request.body
        if(newAdm.role <= 8) {
            return ctx.app.emit('error', isNotAdm, ctx)
        }
        await next()
    } catch {
        return console.error('更新管理员出错')
    }
}

module.exports = {
    lognameExisted,
    admIdisExist,
    isTheBestRole,
    checkRoleisAdm
}